
import requests
import json
import hashlib
import time
from datetime import datetime

class OzonClient:
    """
    Ozon API客户端类，用于与Ozon卖家API进行交互
    """
    def __init__(self, client_id=None, api_token=None):
        self.base_url = "https://api-seller.ozon.ru"
        self.client_id = client_id
        self.api_token = api_token
        self.session = requests.Session()

    def set_credentials(self, client_id, api_token):
        """设置API凭证"""
        self.client_id = client_id
        self.api_token = api_token

    def _make_request(self, method, endpoint, data=None):
        """
        发送API请求
        :param method: HTTP方法 (GET, POST, PUT, DELETE)
        :param endpoint: API端点
        :param data: 请求数据
        :return: API响应
        """
        headers = {
            "Client-Id": self.client_id,
            "Api-Key": self.api_token,
            "Content-Type": "application/json"
        }
        url = f"{self.base_url}{endpoint}"
        # url = f"{self.base_url}"
        print("request url:", url)
        response = None
        try:
            if method.upper() == "GET":
                print("GET params:", data)
                response = self.session.get(url, headers=headers, params=data)
            else:
                print("Request method:", method.upper())
                print("Request headers:", headers)
                print("Request json:", data)
                response = self.session.request(method, url, headers=headers, json=data)

            # 打印发送的低级请求信息（如果可用）
            req = getattr(response, "request", None)
            if req is not None:
                try:
                    body = req.body
                    if isinstance(body, (bytes, bytearray)):
                        body = body.decode("utf-8", errors="replace")
                except Exception:
                    body = req.body
            print("Sent request -> method:", req.method)
            print("Sent request -> url:", req.url)
            try:
                print("Sent request -> headers:", dict(req.headers))
            except Exception:
                print("Sent request -> headers:", req.headers)
            print("Sent request -> body:", body)

            # 打印响应信息
            print("Response status:", response.status_code)
            try:
                print("Response headers:", dict(response.headers))
            except Exception:
                print("Response headers:", response.headers)
            try:
                print("Response json:", response.json())
            except ValueError:
                print("Response text:", response.text)

            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"API请求错误: {e}")
            try:
                if response is not None:
                    print("Error response text:", response.text)
            except Exception:
                pass
            return {"error": str(e)}

    def get_company_info(self):
        """
        获取公司信息
        :return: 公司信息JSON
        """
        # return self._make_request("POST", "/v1/description-category/tree")
        # return self._make_request("POST", "/v1/roles")
        # return self._make_request("POST", "/v1/seller/ozon-logistics/info")
        # data = {
        #     "offer_id": "101pl7271_ob_b9mRN",
        #     "product_id": "2961490426",
        #     "sku": "2961490426"
        # }
        # return self._make_request("POST", "/v1/product/info/description", data)
        # return self._make_request("POST", "/v1/product/info/description", data)

        data = {
            "cursor": "",
            "filter": {
                "product_id": ["2961490426"],
                "offer_id": ["101pl7271_ob_b9mRN"],
                "visibility": "ALL"
            },
            "limit": 100
        }
        return self._make_request("POST", "/v5/product/info/prices", data)

    def get_shop_info(self):
        """
        获取店铺信息
        :return: 店铺信息JSON
        """
        data =  {
            "filter": {},
            "last_id": "",
            "limit": 100
        }
        return self._make_request("POST", "/v3/product/list", data)

    def get_products(self, limit=10, offset=0):
        """
        获取商品列表
        :param limit: 返回的商品数量限制
        :param offset: 分页偏移量
        :return: 商品列表JSON
        """
        # data = {
            
        #     "limit": 100,
        #     "offset": offset
        # }
        data =  {
            "filter": {},
            "last_id": "",
            "limit": 100
        }
        return self._make_request("POST", "/v3/product/list", data)

    def create_product(self, product_data):
        """
        创建并上架新产品
        :param product_data: 产品数据
        :return: 创建结果JSON
        """
        return self._make_request("POST", "/v1/product/import", product_data)

    def get_product_info(self, product_id):
        """
        获取特定商品信息
        :param product_id: 商品ID
        :return: 商品信息JSON
        """
        data = {"product_id": product_id}
        return self._make_request("POST", "/v1/product/info", data)

    def get_product_prices(self, product_ids=None, offer_ids=None):
        """
        获取商品价格信息
        :param product_ids: 商品ID列表
        :param offer_ids: 商品货号列表
        :return: 商品价格信息JSON
        """
        data = {
            "filter": {}
        }
        
        if product_ids:
            data["filter"]["product_id"] = product_ids
        if offer_ids:
            data["filter"]["offer_id"] = offer_ids
            
        data["limit"] = 1000
        return self._make_request("POST", "/v5/product/info/prices", data)

    def get_product_stocks(self, product_ids=None, offer_ids=None):
        """
        获取商品库存信息
        :param product_ids: 商品ID列表
        :param offer_ids: 商品货号列表
        :return: 商品库存信息JSON
        """
        data = {
            "filter": {}
        }
        
        if product_ids:
            data["filter"]["product_id"] = product_ids
        if offer_ids:
            data["filter"]["offer_id"] = offer_ids
            
        data["limit"] = 1000
        return self._make_request("POST", "/v4/product/info/stocks", data)
